#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
台球桌管理API路由
"""

from flask import Blueprint, request, jsonify
from models.table import BilliardTable
from models.order import Order
from database import db
from utils.decorators import admin_required
from datetime import datetime

table_bp = Blueprint('table', __name__)

@table_bp.route('/', methods=['GET'])
def get_tables():
    """获取台球桌列表（公开接口）"""
    try:
        status = request.args.get('status', '')
        table_type = request.args.get('table_type', '')
        area = request.args.get('area', '')
        
        query = BilliardTable.query
        
        if status:
            query = query.filter(BilliardTable.status == status)
        
        if table_type:
            query = query.filter(BilliardTable.table_type == table_type)
        
        if area:
            query = query.filter(BilliardTable.area == area)
        
        tables = query.order_by(BilliardTable.table_no).all()
        
        return jsonify({
            'success': True,
            'data': [table.to_dict() for table in tables]
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取台球桌列表失败: {str(e)}'}), 500

@table_bp.route('/admin', methods=['GET'])
@admin_required
def get_tables_admin(admin):
    """获取台球桌列表（管理员）"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status', '')
        
        query = BilliardTable.query
        
        if search:
            query = query.filter(or_(
                BilliardTable.table_no.like(f'%{search}%'),
                BilliardTable.table_name.like(f'%{search}%')
            ))
        
        if status:
            query = query.filter(BilliardTable.status == status)
        
        pagination = query.order_by(BilliardTable.table_no).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        tables = pagination.items
        
        return jsonify({
            'success': True,
            'data': {
                'tables': [table.to_dict() for table in tables],
                'pagination': {
                    'page': page,
                    'pages': pagination.pages,
                    'per_page': per_page,
                    'total': pagination.total,
                    'has_prev': pagination.has_prev,
                    'has_next': pagination.has_next
                }
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'message': f'获取台球桌列表失败: {str(e)}'}), 500

@table_bp.route('/', methods=['POST'])
@admin_required
def create_table(admin):
    """创建台球桌"""
    try:
        data = request.get_json()
        
        # 检查台桌编号是否已存在
        if BilliardTable.query.filter_by(table_no=data['table_no']).first():
            return jsonify({'success': False, 'message': '台桌编号已存在'}), 400
        
        table = BilliardTable(
            table_no=data['table_no'],
            table_name=data['table_name'],
            table_type=data['table_type'],
            size=data.get('size'),
            brand=data.get('brand'),
            area=data.get('area'),
            floor=data.get('floor'),
            position=data.get('position'),
            hourly_rate=data['hourly_rate'],
            member_rate=data.get('member_rate'),
            peak_rate=data.get('peak_rate'),
            is_premium=data.get('is_premium', False),
            has_lighting=data.get('has_lighting', True),
            has_scoreboard=data.get('has_scoreboard', False),
            remark=data.get('remark')
        )
        
        db.session.add(table)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '台球桌创建成功',
            'data': table.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'创建台球桌失败: {str(e)}'}), 500

@table_bp.route('/<int:table_id>/status', methods=['PUT'])
@admin_required
def update_table_status(admin, table_id):
    """更新台球桌状态"""
    try:
        table = BilliardTable.query.get(table_id)
        if not table:
            return jsonify({'success': False, 'message': '台球桌不存在'}), 404
        
        data = request.get_json()
        new_status = data.get('status')
        
        if not new_status:
            return jsonify({'success': False, 'message': '缺少状态参数'}), 400
        
        old_status = table.status
        table.status = new_status
        table.updated_at = datetime.now()
        
        # 如果设为维护中或禁用，清除当前使用信息
        if new_status in ['maintenance', 'disabled']:
            table.current_user_id = None
            table.current_order_id = None
            table.occupied_since = None
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '台球桌状态更新成功',
            'data': {
                'table_id': table_id,
                'old_status': old_status,
                'new_status': new_status
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': f'更新台球桌状态失败: {str(e)}'}), 500